# 读写文件
# mode
# r : 读文件
# w : 覆盖写文件
# a : 追加文件
# 读文件
f = open("data/students.txt", mode='r', encoding="utf8")
print(f.read(10))  # 读10个字符
print(f.readline())  # 读一行
print(f.readlines())  # 将所有数据都读出来并将每一条数据作为list中的每个元素返回

# 用完记得关闭
f.close()

# 写文件
f2 = open("data/new_stu.txt", mode='a')
f2.write("aaaaa\n")
f2.writelines(['abc\n', 'efg\n'])

# 用完记得关闭
f2.close()

# with open
# 会对打开的连接 例如 IO流 、数据库连接 在用完后会自动关闭
# 读取students.txt 并写入 new_stu2.txt
with open("data/students.txt", mode='r', encoding="utf8") as f:
    with open("data/new_stu2.txt", mode='w', encoding='utf8') as f2:
        f2.writelines(f.readlines())

# 操作MySQL
# pip install pymysql
import pymysql

with pymysql.connect(user='root'
        , password='123456'
        , host='master'
        , port=3306
        , db='student') as conn:
    cur = conn.cursor()
    with open("data/students.txt", encoding='utf8') as f:
        for line in f.readlines():
            id, name, age, gender, clazz = line.split(",")
            cur.execute("insert into student values(%s,%s,%s,%s,%s)", (id, name, age, gender, clazz))
        # 提交插入、修改数据的操作到mysql
        conn.commit()
        # 如果发生了异常
        # conn.rollback()  # 回滚

# 1、创建连接
with pymysql.connect(user='root'
        , password='123456'
        , host='master'
        , port=3306
        , db='student') as conn:
    # 2、创建cursor游标
    cur = conn.cursor()
    # 3、执行SQL
    cur.execute("select * from student limit 10")
    # 4、使用fetchone、fetchall、fetchmany获取数据
    for id, name, age, gender, clazz in cur.fetchall():
        print(name, gender)
